<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/**
 * Video services
 *
 * @version $Id: PhpFox_ServiceVideo.class.php 479 2008-08-06 12:39:25Z phpfoxsv $
 * @package module.core
 * @author Raymond Benc aka natio <www.raybenc.com>
 */
class PhpFox_Mod_Video_ServiceVideo extends BaseService
{
	function _loadExtension()
	{
		$sExtension = "ffmpeg";
		$sExtensionSoname = $sExtension . "." . PHP_SHLIB_SUFFIX;
		$sExtensionFullname = PHP_EXTENSION_DIR . "/" . $sExtensionSoname;
		if (!extension_loaded($sExtension))
		{
    		@dl($sExtensionSoname);
		}
	}	
	
	function getCategories()
	{
		$aRows = $this->oDatabase->getRows("SELECT list_id,list_name,list_total FROM ". App::getT('videos_list') ."");
		foreach ($aRows as $iKey => $aRow)
		{
			$aRows[$iKey]['list_name'] = App::formatTranslate($aRow['list_name']);
		}
		return $aRows;
	}

	function removeHotVideo()
	{
		$this->oDatabase->update(App::getT('sys_sett'), array('val' => ''), " code = 'vid_hot_video' ");
		App::deleteSetting();
		return true;
	}

	function editVideo($aPost)
	{
		$aQuery = array
		(
			'vid_list_id' => $aPost['vid_list_id'],
			'vid_title' => $aPost['vid_title'],
			'vid_info' => $aPost['vid_info'],
			'vid_tags' => $aPost['vid_tags'],
			'stream_id' => (isset($aPost['stream_id']) ? $aPost['stream_id'] : ''),
			'vid_url' => (isset($aPost['vid_url']) ? $aPost['vid_url'] : '')
		);

		$this->oDatabase->update(App::getT('videos'), $aQuery, " vid_id = '". $aPost['vid_id'] ."' AND vid_userid = '". App::getUser('id') ."' ");

		return true;
	}

	function getUsedSpace($sUser)
    {
        $aRows = $this->oDatabase->getRows('SELECT v.vid_id, v.vid_type '.
        									' FROM '.App::getT('videos').' AS v '.
        									' LEFT JOIN '. App::getT('user') .' AS u ON(u.user = "'. $sUser .'")'.
                                            ' WHERE u.id = v.vid_userid');
        $iSize = 0;
        foreach ($aRows as $aRow)
        {
        	$sPath = App::getParam('video.image.path');
        	$sPathFile = App::getParam('video.path');
            $iSize += (file_exists($sPath.$aRow['vid_id'].'.jpg')) ? filesize($sPath.$aRow['vid_id'].'.jpg') : 0;
            $iSize += ($aRow['vid_type'] ? (file_exists($sPathFile.$aRow['vid_id'].'.'.$aRow['vid_type']) ? filesize($sPathFile.$aRow['vid_id'].'.' . $aRow['vid_type']) : 0) : '');
        }
		return $iSize;
    }

    function addPendingVideo($aPost)
    {
		$aQuery = array
		(
			'vid_list_id' => $aPost['vid_list_id'],
			'vid_userid' => (!isset($aPost['vid_userid']) ? App::getUser('id') : $aPost['vid_userid']),
			'vid_title' => $aPost['vid_title'],
			'vid_info' => $aPost['vid_info'],
			'vid_type' => (isset($aPost['vid_type']) ? $aPost['vid_type'] : ''),
			'vid_time' => time(),
			'vid_url' => (isset($aPost['vid_url']) ? $aPost['vid_url'] : ''),
			'stream_id' => (isset($aPost['stream_id']) ? $aPost['stream_id'] : ''),
			'vid_tags' => (isset($aPost['vid_tags']) ? $aPost['vid_tags'] : ''),
		);

		$iId = $this->oDatabase->insert(App::getT('videos_pending'), $aQuery);
		
		if (((isset($aPost['vid_url'])) && $aPost['vid_url']))
		{
			$this->getStreamImage($iId, $aPost['vid_url'], $aPost['stream_id']);
		}

		return $iId;
    }

    function deletePendingVideo($iId)
    {
    	$this->oDatabase->_delete(App::getT('videos_pending'), " vid_id = '". $iId ."' ");

    	$sPendingFile = App::getParam('video.image.path') . "pending_". $iId .".jpg";
    	if ( file_exists($sPendingFile) )
    	{
    		unlink($sPendingFile);
    	}
    	
    	$sPendingFile = App::getParam('video.path') . "pending_". $iId .".flv";
    	if ( file_exists($sPendingFile) )
    	{
    		unlink($sPendingFile);
    	}    	
    	
    	return true;
    }

	function renamePendingImage($iOldId, $iNewId, $sExt = "")
	{
		$sFileDestPath = App::getParam('video.path') . "pending_". $iOldId . "." . $sExt;
		$sFileNewFile = App::getParam('video.path') . $iNewId . "." . $sExt;
		if ( file_exists($sFileDestPath) )
		{
			rename($sFileDestPath, $sFileNewFile);
		}

		$sDestPath = App::getParam('video.image.path') . "pending_". $iOldId .".jpg";
		$sNewFile = App::getParam('video.image.path') . $iNewId .".jpg";
		if ( file_exists($sDestPath) && !file_exists($sNewFile) )
		{
			rename($sDestPath, $sNewFile);
		}
		
		if (file_exists($sDestPath))
		{
			@unlink($sDestPath);
		}

		return false;
	}

	function doDebug($sStr)
	{
		if ( !App::getParam('debug') )
		{
			return;
		}
		if ( is_array($sStr) )
		{
			$sStr = print_r($sStr, true);
		}
		$hFile = fopen(App::getParam('path') . 'file/cache/video.log', 'a+');
		fwrite($hFile, $sStr . "\n");
		fclose($hFile);
	}

	function convertVideo($iId, $sType = "")
	{
		$this->_loadExtension();
		
		$sDestPath = (App::getParam('vid_approve') ? "pending_" : '') . $iId;
		
		$sSource = App::getParam('video.path') . $sDestPath . "." . $sType;
		$sDestination = App::getParam('video.path') . $sDestPath . ".flv";
		$sImageLocation = App::getParam('video.image.path') . $sDestPath . ".jpg";
		$sPathToMencoder = App::getParam('ffmpeg_mencoder');
		$sPathToFfmpeg = App::getParam('ffmpeg_location');
			
		$aNotSupported = array
		(
			'swf',
		);

		if ( !file_exists($sSource) || in_array($sType, $aNotSupported) )
		{
			return false;
		}

		if ( $sType != 'flv' )
		{
			$this->doDebug('## Start converting: '. $sSource .' ##');
			
			switch($sType)
			{
				case 'wmv':
				case 'avi':
		    			$this->doDebug('Trying WMV...');
		    			$sCmd = "$sPathToFfmpeg -i {$sSource} -copyts -ar 44100 -s 320x240  {$sDestination}";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');					
					break;
					
				default:
			
		    		//the following can be changed (vbitrate, vop scale, SRATE)
		    		$this->doDebug('Trying STEP 1...');
		    		$sCmd = "$sPathToMencoder {$sSource} -o {$sDestination} -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vf scale=450:400 -srate 22050";
		    		@exec("$sCmd 2>&1", $mOutput);
		    		$this->doDebug($sCmd);
		    		$this->doDebug($mOutput);
		    		$this->doDebug('Done!');
		
		    		//If no flv was created. Attempt to convert with -vop swicth and not -vf
		    		if(!file_exists($sDestination))
		    		{
		        		$this->doDebug('Trying STEP 2...');
		        		$sCmd = "$sPathToMencoder {$sSource} -o {$sDestination} -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -vop scale=450:400 -srate 22050";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');
		    		}
		
		    		//If no flv was created. Attempt to convert with no -lavcopts i_certify_etc_etc
		    		if(!file_exists($sDestination))
		    		{
		    			$this->doDebug('Trying STEP 3...');
		    			$sCmd = "$sPathToMencoder {$sSource} -o {$sDestination} -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=800:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=450:400 -srate 22050";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');
		    		}
		    		
		    		//Simple mencoder
		    		if(!file_exists($sDestination))
		    		{
		    			$this->doDebug('Trying STEP 4...');
		    			$sCmd = "$sPathToMencoder -ovc lavc -oac pcm -o $sDestination {$sSource}";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');
		    		}
					
					// FFMPEG with mp3 acodec
					if(!file_exists($sDestination))
		    		{
		    			$this->doDebug('Trying STEP 5...');
		    			$sCmd = "$sPathToFfmpeg -acodec mp3 -y -i {$sSource} -ab 32 -ac 1 -ar 44100  {$sDestination}";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');
		    		}
		    		
		    		// Simple FFMPEG
					if(!file_exists($sDestination))
		    		{
		    			$this->doDebug('Trying STEP 6...');
		    			$sCmd = "$sPathToFfmpeg  -y -i {$sSource} {$sDestination}";
		    			@exec("$sCmd 2>&1", $mOutput);
		    			$this->doDebug($sCmd);
		    			$this->doDebug($mOutput);
		    			$this->doDebug('Done!');
		    		}
					
					if(!file_exists($sDestination))
					{
						$this->doDebug('Trying STEP 7...');
						unset($sOutput);
						if (App::getParam('mp3lame_convert'))
						{
							exec("". App::getParam('ffmpeg_mencoder') ." {$sSource} -o ". str_replace('.flv', '.avi', $sDestination) ." -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -srate 22050", $sOutput, $sReturn);
						}
						else
						{
							exec("". App::getParam('ffmpeg_mencoder') ." -ovc lavc -oac pcm -o ". str_replace('.flv', '.avi', $sDestination) ." {$sSource}", $sOutput, $sReturn);
						}
						$this->doDebug('Creating '. str_replace('.flv', '.avi', $sDestination) .' from '. $sSource .'');
						$this->doDebug($sOutput);
						unset($sOutput);
						if (App::getParam('mp3lame_convert'))
						{
							exec("". App::getParam('ffmpeg_location') ." 2>&1 ". str_replace('.flv', '.avi', $sDestination) ." -o {$sDestination} -of lavf -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -srate 22050", $sOutput, $sReturn);
						}
						else
						{
							exec("". App::getParam('ffmpeg_location') ." 2>&1 -y -i ". str_replace('.flv', '.avi', $sDestination) ." {$sDestination}", $sOutput, $sReturn);
						}
						$this->doDebug("EXEC: ". App::getParam('ffmpeg_location') ." 2>&1 -i ". str_replace('.flv', '.avi', $sDestination) ." {$sDestination}");
						$this->doDebug('Creating '. $sDestination .' from '. str_replace('.flv', '.avi', $sDestination) .'');
						$this->doDebug($sOutput);
						$this->doDebug('Done!');
					}
			}			
				
			$this->doDebug("Converting done!\n\n");
		}
		
		if ($sType != 'flv' && class_exists('ffmpeg_movie'))
		{
			$this->doDebug("Loading ffmpeg_movie()\n");
			$oFfmpegMovie = new ffmpeg_movie($sSource);
			$this->doDebug('Done!');
	
			$this->doDebug("Loading ffmpeg_movie::getFrame()\n");
			$oFrame = $oFfmpegMovie->getFrame(App::getParam('ffmpeg_frames'));
			$this->doDebug('Done!');
	
			$this->doDebug('Creating image for video...');
			if (is_object($oFrame) && method_exists($oFrame, 'toGDImage'))
			{
				$mImage = $oFrame->toGDImage();
				$this->doDebug('Using toGDImage()');
				if ( $mImage )
				{
					@imagejpeg($mImage, $sImageLocation, 100);
					@imagedestroy($mImage);
				}
			}
		}
			
		if (!file_exists($sImageLocation))
		{
			$this->doDebug('toGDImage() not valid so we are trying with ffmpeg...');
			$sCmd = "$sPathToFfmpeg -i $sDestination -ss " . App::getParam('ffmpeg_frames') . " -t 00:00:01 -s 120x120 -r 1 -f mjpeg $sImageLocation";
			@exec("$sCmd 2>&1", $sOutput);
    		$this->doDebug($sOutput);
    			
    		if (!file_exists($sImageLocation))
    		{
    			$this->doDebug('mjpeg did not work so we are trying image2...');
    			$sCmd = "$sPathToFfmpeg -i $sDestination -ss " . App::getParam('ffmpeg_frames') . " -t 00:00:01 -s 120x120 -r 1 -f image2 $sImageLocation";
    			@exec("$sCmd 2>&1", $sOutput);
    			$this->doDebug($sOutput);
    		}
		}
		$this->doDebug('Done!');

		if (class_exists('ffmpeg_movie'))
		{
			$oMtime = new ffmpeg_movie($sSource);
			if (method_exists($oMtime, 'getDuration'))
			{
				$iDuration = $oMtime->getDuration();
				$this->oDatabase->update(App::getT('videos'), array('duration' => $iDuration, 'filesize' => filesize($sSource)), " vid_id = '". $iId ."' ");
				$this->doDebug('Error: Duration updated');
			}
			else 
			{
				$this->doDebug('Error: Duration no updated');
			}
		}
			
		if (file_exists($sImageLocation))
		{
			$this->doDebug('Creating thumbnail...');
			App::loadClass('file/Image');
	       	$oImage = &new file_Image();
	       	$oImage->loadInfo($sImageLocation);
			$oImage->makeThumbnail($sImageLocation, 120, 120);
			$this->doDebug('Done!');
		}
		else
		{
			$this->doDebug('Error: Image not created!');
		}

		if ($sType != 'flv')
		{
			$this->doDebug('Removing source file');
			@unlink($sSource);
		}
		

		$this->oDatabase->update((App::getParam('vid_approve') ? App::getT('videos_pending') : App::getT('videos')), array('vid_type' => 'flv'), " vid_id = '". $iId ."' ");

		return true;
	}

    function approveVideo($iId)
    {
    	$aPost = $this->oDatabase->getRow("SELECT * FROM ". App::getT('videos_pending') ." WHERE vid_id = '". $iId ."'");
    	if ( isset($aPost['vid_id']) )
    	{
    		$this->addVideo($aPost, true);
    		$this->oDatabase->_delete(App::getT('videos_pending'), " vid_id = '". $iId ."' ");
    		return true;
    	}
    }

	function addVideo($aPost, $bUserId = false)
	{
		$aQuery = array
		(
			'vid_list_id' => $aPost['vid_list_id'],
			'vid_userid' => (!$bUserId ? App::getUser('id') : $aPost['vid_userid']),
			'vid_title' => $aPost['vid_title'],
			'vid_info' => $aPost['vid_info'],
			'vid_type' => (isset($aPost['vid_type']) ? $aPost['vid_type'] : ''),
			'vid_time' => time(),
			'vid_url' => (isset($aPost['vid_url']) ? $aPost['vid_url'] : ''),
			'stream_id' => (isset($aPost['stream_id']) ? $aPost['stream_id'] : ''),
			'vid_tags' => (isset($aPost['vid_tags']) ? $aPost['vid_tags'] : ''),
		);

		$iId = $this->oDatabase->insert(App::getT('videos'), $aQuery);

		if ( !App::getParam('vid_approve') && ((isset($aPost['vid_url'])) && $aPost['vid_url']) )
		{
			$this->getStreamImage($iId, $aPost['vid_url'], $aPost['stream_id']);
		}

		if ( App::getParam('vid_approve') && isset($aPost['vid_id']))
		{
			$this->renamePendingImage($aPost['vid_id'], $iId, (isset($aPost['vid_type']) ? $aPost['vid_type'] : ''));
		}

		$oSecurityService = &App::getModuleService('Account', 'Security');
		$oAccountService = &App::getModuleService('Account', 'Account');
		if (App::getParam('vid_approve'))
		{
			$oAcc = $oAccountService->getById($aPost['vid_userid']);
		}
		$oAccountService->changeUserInfo((App::getParam('vid_approve') ? $oAcc : $oSecurityService->getCurrentUser()), 'video');
		
		return $iId;
	}

	function displayVideo($sParam)
	{
		if ( !isset($sParam['vid_url']) )
		{
			return '';
		}

		$sVidUrl =   (!empty($sParam['vid_url']) ? $this->getStreamLocation($sParam['stream_id'], $sParam['vid_url']) : $sParam['vid_id'].'.'.$sParam['vid_type']);
		//$sVidUrl = (!empty($sParam['vid_url']) ? $this->getStreamLocation($sParam['stream_id'], $sParam['vid_url']) : App::getParam('video.url') . ''. $sParam['vid_id'] .'.'. $sParam['vid_type'] .'');
		
		if ($sParam['vid_type'] != 'flv' && file_exists(App::getParam('video.path') . $sParam['vid_id'] . '.flv'))
		{
			$sVidUrl = str_replace($sParam['vid_type'], 'flv', $sVidUrl);
		}
		
		return $sVidUrl;
	}

	function prepareStars($iRating)
	{
		$iRating = round($iRating);

		$showStars = array(false, false, false, false, false);

		if ( $iRating == 5)
		{
			$showStars = array(true, true, true, true, true);
		}
		elseif ( $iRating ==4)
		{
			$showStars = array(true, true, true, true, false);
		}
		elseif ( $iRating == 3)
		{
			$showStars = array(true, true, true, false, false);
		}
		elseif ( $iRating == 2)
		{
			$showStars = array(true, true, false, false, false);
		}
		elseif ( $iRating == 1)
		{
			$showStars = array(true, false, false, false, false);
		}

		return $showStars;
	}

	function isAllowedExt($sStr)
	{
		$aAllowedExt = array();
		$aGetExt = split(",", App::getParam('vid_allowed_ext'));
		foreach($aGetExt as $aFinal)
		{
			$aFinal = trim($aFinal);
			if ( !empty($aFinal) )
			{
				$aAllowedExt[] = strtolower($aFinal);
			}
		}

		$sExt = substr(strtolower($sStr), -4);

		if ( in_array($sExt, $aAllowedExt) )
		{
			return true;
		}

		return false;
	}

	/**
	 * Import Videos
	 *
	 * @deprecated v1.6 RC2
	 */
	function importVideo($aItem, $sLocation)
	{
		return false;
		
		App::loadClass('file/File');

		switch($aItem['stream_id'])
		{
			// YouTube
			case 1:
			$sData = CFile::getContent($aItem['vid_url']);
			if ( $sData )
			{
				preg_match('#/watch_fullscreen\?video_id=([a-z0-9-_]+)&l=([0-9]+)&t=([a-z0-9-_]+)#i', $sData, $aMatches);
				if ( (isset($aMatches[1]) && isset($aMatches[2]) && isset($aMatches[3])) && (ereg($aMatches[1], $aItem['vid_url'])) )
				{
					$sUrl = "http://www.youtube.com/get_video?video_id=". $aMatches[1] ."&l=". $aMatches[2] ."&t=". $aMatches[3] ."";
				}
			}
			break;

			// Google
			/*
			case 2:

			$sTempUrl = $aItem['vid_url'];
			$sTempUrl = explode("docid=", $sTempUrl);
			$sTempUrl = explode("&", $sTempUrl[1]);
			if ( $sTempUrl[0] )
			{
				$sNewUrl = 'http://video.google.com/videohosted?docid='. $sTempUrl[0] .'';
				$sData = CFile::getContent($sNewUrl);
				$aCheck = explode("googleplayer.swf?&videoUrl\u003d", $sData);
				$aCore = explode('\"', $aCheck[1]);
				$aGoogleUrl = urldecode($aCore[0]);
				$sUrl = $aGoogleUrl;
			}
			break;
			*/
		}

		if ( isset($sUrl) )
		{
			$sFlvFile = App::getParam('video.path') . $sLocation . $aItem['vid_id'] . ".flv";
			$sImageLocation = App::getParam('video.image.path') . $sLocation . $aItem['vid_id'] . ".jpg";

			if ( !CFile::copyContent($sUrl, $sFlvFile) )
			{
				return false;
			}

			/*
			$oFfmpegMovie = new ffmpeg_movie($sFlvFile);

			$oFrame = $oFfmpegMovie->getFrame(App::getParam('ffmpeg_frames'));

			if ( is_object($oFrame) )
			{
				$mImage = $oFrame->toGDImage();

				if ( $mImage )
				{
					@imagejpeg($mImage, $sImageLocation, 100);
					@imagedestroy($mImage);

					$oMtime = new ffmpeg_movie($sFlvFile);
					$iDuration = $oMtime->getDuration();

					if ( !$sLocation )
					{
						$this->oDatabase->update(App::getT('videos'), array('vid_type' => 'flv', 'vid_url' => '', 'duration' => $iDuration, 'filesize' => filesize($sFlvFile)), " vid_id = '". $aItem['vid_id'] ."' ");
					}

					App::loadClass('file/Image');
        	    	$oImage = &new file_Image();
        	    	$oImage->loadInfo($sImageLocation);
					$oImage->makeThumbnail($sImageLocation, 120, 120);
				}
			}
			*/

			return true;
		}

		return false;
	}

	function getStreamLocation($iStream_id, $sUrl)
	{
		static $sCacheUrl;
		
		if ($sCacheUrl)
		{
			return $sCacheUrl;
		}
		
		switch($iStream_id)
		{
			// YouTube
			case 1:
			$aPart = explode('youtube.com', $sUrl);
			if ( isset($aPart[0]) )
			{
				$aPart2 = explode('http://', $aPart[0]);
				if ( isset($aPart2[1]) )
				{
					$sUrl = str_replace($aPart2[1], 'www.', $sUrl);
				}
			}
			$sUrl = str_replace("watch?v=", "v/", $sUrl) . (App::getParam('youtube_related') ? "" : "&rel=0");
			$sExt = "swf";
			break;

			// Google
			case 2:
			// http://video.google.com/googleplayer.swf?docId=$ID&hl=en			
			
			if (($sGoogle = @file_get_contents($sUrl)) && preg_match("/youtube.com\/watch\?v=(.*)/i", $sGoogle, $aMatch) && isset($aMatch[1]))
			{			
				$aPart = explode('">', $aMatch[1]);
				return $this->getStreamLocation(1, 'http://www.youtube.com/watch?v=' . $aPart[0]);
			}
			else 
			{			
				$sUrl = str_replace("videoplay", "googleplayer.swf", $sUrl);
			}
			
			break;

			// Myspace
			case 3:
			// http://lads.myspace.com/videos/myspacetv_vplayer0005.swf?m=$ID&type=video
			$aGetId = explode("videoid=", strtolower($sUrl));
			if (isset($aGetId[1]))
			{
				$aGetId = explode("&", $aGetId[1]);
				$sUrl = 'http://lads.myspace.com/videos/myspacetv_vplayer0005.swf?m='. $aGetId[0] .'&type=video';
			}
			break;

			// Bolt
			case 4:
			// http://www.bolt.com/video/flv_player_branded.swf?contentId=$ID6&contentType=2
			$aGetId = explode("/", $sUrl);
			foreach($aGetId as $aId)
			{
				if ( is_numeric($aId) )
				{
					$iFinalId = $aId;
					break;
				}
			}
			if ( isset($iFinalId) )
			{
				$sUrl = 'http://www.bolt.com/video/flv_player_branded.swf?contentId='. $iFinalId .'&contentType=2';
			}
			break;

			// Dailymotion
			case 5:

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $sUrl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$result = curl_exec($ch);
			curl_close($ch);

			if(preg_match("/param name=\"flashvars\" value=\"url=(.*\.flv.*\.flv)/Ui", $result, $d_link))
			{
				$aGetId = explode("&url=", urldecode($d_link[1]));
				if ( isset($aGetId[0]) )
				{
					$aGetId = explode("&", $aGetId[1]);
					$sUrl = $aGetId[0];
				}
			}
			break;

			// Break
			case 6:

			// http://media1.break.com/dnet/media/$ID1/$ID2.flv
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $sUrl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$result = curl_exec($ch);
			curl_close($ch);

			if(preg_match("/sGlobalFileName=(.*)/", $result, $d_link))
			{
				$name = explode("sGlobalFileName='", $d_link[0]);
				if ( isset($name[1]) )
				{
					$name = explode("';", $name[1]);

					if ( isset($name[4]) )
					{
						$page = explode("sGlobalContentFilePath='", $name[4]);

						if ( isset($page[1]) )
						{
							$sUrl = 'http://media1.break.com/dnet/media/'. $page[1] .'/'. $name[0] .'.flv';
						}
					}
				}
			}
			else
			{
				$aContent = explode("so.addVariable('videoPath', '", $result);
				$aContent = explode("');", $aContent[1]);
				if ( isset($aContent[0]) && substr($aContent[0], 0, 7) == 'http://' )
				{
					$sUrl = $aContent[0];
				}

			}
			
			break;

			// iFilm
			case 7:

			// http://www.ifilm.com/efp?flvbaseclip=$ID
			$aGetId = explode("/", $sUrl);
			foreach($aGetId as $aId)
			{
				if ( is_numeric($aId) )
				{
					$iFinalId = $aId;
					break;
				}
			}
			if ( isset($iFinalId) )
			{
				$sUrl = 'http://www.spike.com/efp?flvbaseclip='. $iFinalId .'';
			}

			break;
		}
		
		$sCacheUrl = $sUrl;

		return $sUrl;
	}

	function getStreamImage($iId, $sUrl, $iStream_id)
	{
		switch($iStream_id)
		{
			// YouTube
			case 1:
			
			$aUrl = parse_url($sUrl);
			parse_str($aUrl['query'], $aStr);
			$sImage = 'http://img.youtube.com/vi/' . $aStr['v'] . '/default.jpg';
			
			break;
			
			case 2:
				
				if (($sGoogle = @file_get_contents($sUrl)) && preg_match("/\<img src=\"http:\/\/video.google.com\/ThumbnailServer(.*)/i", $sGoogle, $aMatch) && isset($aMatch[1]))
				{
					$aPart = explode('"', $aMatch[1]);
					$sImage = 'http://video.google.com/ThumbnailServer' . str_replace('&amp;', '&', $aPart[0]);
				}

				break;

			// Break
			case 6:

			// http://media1.break.com/dnet/media/$ID1/$ID2.flv
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $sUrl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$result = curl_exec($ch);
			curl_close($ch);
			if(preg_match("/sGlobalFileName=(.*)/", $result, $d_link))
			{
				$name = explode("sGlobalFileName='", $d_link[0]);
				if ( isset($name[1]) )
				{
					$name = explode("';", $name[1]);

					if ( isset($name[4]) )
					{
						$page = explode("sGlobalContentFilePath='", $name[4]);

						if ( isset($page[1]) )
						{
							$sImage = 'http://media1.break.com/dnet/media/'. $page[1] .'/'. $name[0] .'.jpg';
						}
					}
				}
			}

			break;

			// iFilm
			case 7:

			// http://img2.ifilmpro.com/resize/image/stills/films/resize/istd/$ID.jpg?width=130
			$aGetId = explode("/", $sUrl);
			foreach($aGetId as $aId)
			{
				if ( is_numeric($aId) )
				{
					$iFinalId = $aId;
					break;
				}
			}
			if ( isset($iFinalId) )
			{
				$sImage = 'http://img2.ifilmpro.com/resize/image/stills/films/resize/istd/'. $iFinalId .'.jpg?width=130';
			}


		}

		if ( isset($sImage) )
		{			
			$sDestPath = App::getParam('video.image.path') . (App::getParam('vid_approve') ? "pending_" : '');
			@copy($sImage, $sDestPath . $iId . ".jpg");
			return true;
		}

		return false;
	}

	function addHot($iId)
	{
		$this->oDatabase->update(App::getT('sys_sett'), array('val' => $iId), " code = 'vid_hot_video' ");
		App::deleteSetting();
		return true;
	}

	function removeFeature($iId)
	{
		$this->oDatabase->update(App::getT('videos'), array('featured' => ''), "vid_id = '". $iId ."'");
		return true;
	}

	function addFeature($iId)
	{
		$this->oDatabase->update(App::getT('videos'), array('featured' => '1'), "vid_id = '". $iId ."'");
		return true;
	}

	function reportVideo($iId, $iReport)
	{
		$this->oDatabase->query("UPDATE ". App::getT('videos') ." SET
			reported = '". $iReport ."'
			WHERE vid_id = '". $iId ."'");

		return true;
	}

	function saveToFavorite($iId)
	{
		$aItem = $this->oDatabase->getRow("SELECT COUNT(*) AS count FROM ". App::getT('videos_favorite') ."
			WHERE video_id = '". $iId ."' AND '". App::getUser('id') ."'");

		if ( $aItem['count'] )
		{
			return false;
		}

		$sSql = array
		(
			'user_id' => App::getUser('id'),
			'video_id' => $iId,
			'time' => time(),
		);

		$this->oDatabase->insert(App::getT('videos_favorite'), $sSql);

		return true;
	}

	function deleteVideo($iId, $bDoCheck = false)
	{
		$aItem = $this->oDatabase->getRow("SELECT vid_id, vid_type FROM ". App::getT('videos') ."
				WHERE `vid_id` = '". $iId ."' ". ($bDoCheck ? "AND `vid_userid` = '". App::getUser('id') ."'" : '') ."");

		if ( !isset($aItem['vid_id']) )
		{
			return false;
		}

		$this->oDatabase->_delete(App::getT('videos'), " vid_id = '". $aItem['vid_id'] ."' ");
		//$this->oDatabase->_delete(App::getT('videos_comments'), " cm_mainid = '". $aItem['vid_id'] ."' ");
		$oCommentService = &App::getModuleService('Comments', 'Comment');
   		/* @var $oCommentService PhpFox_Mod_Comments_ServiceComment */
   		$oCommentService->onVideoDelete($iId);
                
		$this->oDatabase->_delete(App::getT('videos_favorite'), " video_id = '". $aItem['vid_id'] ."' ");
		$this->oDatabase->_delete(App::getT('videos_rating'), " rate_video = '". $aItem['vid_id'] ."' ");

		$sFilePath = App::getParam('video.path') . $aItem['vid_id'] . ".". $aItem['vid_type'];
		if ( file_exists($sFilePath) )
		{
			@unlink($sFilePath);
		}

		$sImagePath = App::getParam('video.image.path') . $aItem['vid_id'] . ".jpg";
		if ( file_exists($sImagePath) )
		{
			@unlink($sImagePath);
		}

		return true;
	}

	function addRating($iId, $iRating)
	{
		 $checkUser = $this->oDatabase->getRow("SELECT COUNT(*) AS count FROM ". App::getT('videos_rating') ."
	 		WHERE rate_userid = '". App::getUser('id') ."' AND rate_video = '". $iId ."'");

	 	if ( !$checkUser['count'] )
	 	{
	 		$this->oDatabase->query("INSERT INTO ". App::getT('videos_rating') ." SET
	 			rate_video = '". $iId ."',
	 			rate_userid = '". App::getUser('id') ."',
	 			rate_count = '". $iRating ."',
	 			rate_time = '". time() ."'
	 		");
			$iTotalRating = 0;
			$query = $this->oDatabase->getRows('SELECT count(*), AVG(`rate_count`) FROM `phpfox_videos_rating` WHERE rate_video ='.$iId);
			$iTotalRating=$query[0]['count(*)'];
			$average = round($query[0]['AVG(`rate_count`)']);
			$this->oDatabase->query("UPDATE ". App::getT('videos') ." SET
				vid_rating = '". $average ."',
				vid_rating_count = '". $iTotalRating ."'
				WHERE vid_id = '". $iId ."'");
			return true;
		}
		return false;
	}

	function check_requirements()
	{
		$this->_loadExtension();
		
		if ( class_exists('ffmpeg_movie') )
		{
			$aMethods = get_class_methods('ffmpeg_movie');
			if (is_array($aMethods))
			{
				if ( in_array('getframe', array_map('strtolower', $aMethods)) )
				{
					return array(true, '');
				}
				else
				{
					$sFail = App::format('Mod_Video.error_video_frame');
				}
			}
			else
			{
				$sFail = App::format('Mod_Video.error_video_frame');
			}
		}
		else
		{
			$sFail = App::format('Mod_Video.error_no_ffmpeg');
		}

		return array(false, $sFail);
	}
	
	function getAccessForContent($sFile)
    {
    	$oCurUser = App::loadUser();
    	if( FALSE===strpos($sFile,'pending_') )
    	{
    		//find from approved:
	    	$iItemId = intval($sFile);
	        if (!$iItemId)
	        {
	        	return FALSE;
	        }
	        
	        $aItem = $this->oDatabase->getRow("
	 			SELECT 
	 				vid_id, vid_userid 
	 			FROM ". App::getT('videos') ." AS vids
				WHERE vids.vid_id = '$iItemId'
				");
	        if(isset($aItem['vid_id']))
	        {
	        	return TRUE;
	        }
        }else{
	    	//find from pending:
        	$iItemId = intval(substr($sFile,8));
	        if (!$iItemId)
	        {
	        	return FALSE;
	        }
	    	$aItem = $this->oDatabase->getRow("
	 			SELECT 
	 				vid_id, vid_userid 
	 			FROM ". App::getT('videos_pending') ." AS vids
				WHERE vids.vid_id = '$iItemId'
				");//d($aItem,1);
	        if($aItem)
	        {
	        	return (App::isStaff() OR $oCurUser->aData['id'] == $aItem['vid_userid']);
	        }
        }
		return FALSE;
    }
}

?>